import {
  chunkArray,
  sendMessage,
  executeSequentially,
  awaitDelayTime,
  sleep,
  calculateMaxInputAmountOptimized,
  parseDateTimeToTs,
  formatTsToDateTime,
  getCurrentTimeText,
} from "../../utils";
import type { TManualVerifyGoods } from "../../type";
import CurrencyConverter from "../../currencyConverter";
import {
  deleteSkc,
  parsePrice,
  findDeleteButton,
  getErpSkuPriceMap,
  showCustomDialog,
} from "./utils";
import ConcurrentExecutor from "../../class/ConcurrentExecutor";

const originUrl = location.origin;

const concurrentExecutor = new ConcurrentExecutor(1);

// 全局 SheetJS 对象声明（通过 content_scripts 外部引入）
declare const XLSX: any;

const converter = new CurrencyConverter();

function scrollToTr(tr: HTMLElement) {
  const tbody = document.querySelector(
    '[class*="mrs_styles__detailContent--"]'
  );
  if (!tbody) return;
  const defaultOffsetTop = 723 + 182 + 55 - 125;
  // 723 -> document.querySelector('[class*="mrs_styles__container--"]').offsetTop
  // 182 -> document.querySelector('.so-table').offsetTop
  // 55 -> document.querySelector('.sso-table-simple-body').offsetTop
  // 125 -> 不知道什么东西根据实际效果弄出来的
  const trOffsetTop = tr.offsetTop;
  if (!trOffsetTop) return;
  tbody.scrollTop = defaultOffsetTop + trOffsetTop;
}

function getSkuCodeByElement(row: Element) {
  let skuCode = "";
  const skuCodeElement = row.querySelector('[class*="mrs_styles__sku--"]');
  if (skuCodeElement) {
    const match = skuCodeElement.textContent?.match(/SKU:\s([a-zA-Z0-9]+)/);

    if (match) {
      skuCode = match[1];
    }
  }
  return skuCode;
}

async function setReactInputValueBySheinPlatform(
  skuCode: string,
  value: number
): Promise<boolean> {
  return new Promise((resolve) => {
    chrome.runtime.sendMessage(
      {
        type: "setReactInputValueBySheinPlatform",
        skuCode,
        value,
      },
      (response) => {
        resolve(response?.success || false);
      }
    );
  });
}

function findPreviousDeleteButton(trElement: Element) {
  // 如果自己有直接返回
  const currentRowFixedRightCell = trElement.querySelector(
    ".so-table-fixed-right,.so-table-fixed-first"
  );

  if (currentRowFixedRightCell) {
    const deleteButton = findDeleteButton(currentRowFixedRightCell);
    if (deleteButton) return deleteButton;
  }

  // 获取当前tr的前一个兄弟元素
  let previousTr = trElement.previousElementSibling;
  // 循环查找前一个兄弟元素
  while (previousTr) {
    const fixedRightCell = previousTr.querySelector(
      ".so-table-fixed-right,.so-table-fixed-first"
    );

    if (fixedRightCell) {
      const deleteButton = findDeleteButton(fixedRightCell);
      if (deleteButton) return deleteButton;
    }

    previousTr = previousTr.previousElementSibling;
  }

  return false;
}

function findRowPriceInfo(trElement: Element) {
  if (!trElement) {
    return null;
  }
  const tds = trElement.getElementsByTagName("td");

  for (let i = 0; i < tds.length; i++) {
    const td = tds[i];
    const targetDiv = td.querySelector("div.so-button-group");

    if (targetDiv && i > 0) {
      const priceTd = tds[i - 1];
      return parsePrice(priceTd.textContent || "");
    }
  }

  return null;
}

async function formatSkuListToSkuInfoMap({
  skuInfoMap,
  platform,
  shopId,
  multiplierMinInput,
  multiplierMaxInput,
  operateMap = {},
}: {
  skuInfoMap: any;
  platform: string;
  shopId: string;
  multiplierMinInput: number;
  multiplierMaxInput: number;
  operateMap: any;
}): Promise<void> {
  const storage = await chrome.storage.sync.get(["baoyiplus_accessToken"]);
  const { baoyiplus_accessToken = "" } = storage;
  if (baoyiplus_accessToken) {
    const skuInfoRowList = document.querySelectorAll(
      ".so-table .so-table-simple-body .so-table-table-bordered .so-table-normal"
    );
    const skuInfoRowMap: any = {};
    const skuCodeList: any[] = [];
    Array.from(skuInfoRowList).forEach((row) => {
      const skuCode = getSkuCodeByElement(row);
      const { price, currency } = findRowPriceInfo(row) || {};

      const currentSkuDelete = findPreviousDeleteButton(row);

      if (!(skuCode in operateMap) && skuCode && currentSkuDelete) {
        operateMap[skuCode] = true;
        skuCodeList.push(skuCode);
        skuInfoRowMap[skuCode] = {
          skuCode,
          currentSkuDelete,
          price,
          currency,
          trElement: row,
        };
      }
    });
    let currentPageUseDelete = false;
    if (!skuCodeList.length) {
      return Promise.resolve();
    }

    const erpSKuPriceMap = await getErpSkuPriceMap({
      skuCodeList,
      shopId,
      platform,
      baoyiplus_accessToken,
    });
    const executeSequentiallyArray: any[] = [];
    const erpCodeInfoMap = Object.entries(erpSKuPriceMap).reduce(
      (obj: any, [outId, value]) => {
        if (outId in skuInfoRowMap) {
          obj[outId] = value;
        }
        return obj;
      },
      {}
    );

    Object.keys(skuInfoRowMap).forEach((outId) => {
      const { currency, price, currentSkuDelete, trElement } =
        skuInfoRowMap[outId];
      if (outId in erpCodeInfoMap) {
        const { sourcePrice, sourceCurrency } = erpCodeInfoMap[outId];
        executeSequentiallyArray.push(async () => {
          const editInputPrice = await converter.convert(
            sourcePrice,
            sourceCurrency,
            currency
          );
          const finallyPrice = calculateMaxInputAmountOptimized({
            currencyPrice: Number(price),
            reduceRateRange: { min: 0.05, max: 0.8 }, // 这边不是范围而是最大值
            multiplierMinInput,
            multiplierMaxInput,
            purchasePrice: editInputPrice,
          });
          if (finallyPrice) {
            scrollToTr(trElement);
            return setReactInputValueBySheinPlatform(outId, finallyPrice);
          } else {
            if (!document.contains(currentSkuDelete)) {
              return Promise.resolve(true);
            }
            scrollToTr(trElement);
            currentPageUseDelete = true;
            return deleteSkc(currentSkuDelete);
          }
        });
      } else {
        executeSequentiallyArray.push(() => {
          if (!document.contains(currentSkuDelete)) {
            return Promise.resolve(true);
          }
          scrollToTr(trElement);
          currentPageUseDelete = true;
          return deleteSkc(currentSkuDelete);
        });
      }
    });

    return executeSequentially(executeSequentiallyArray).then(() => {
      if (currentPageUseDelete) {
        return formatSkuListToSkuInfoMap({
          skuInfoMap,
          platform,
          shopId,
          multiplierMinInput,
          multiplierMaxInput,
          operateMap,
        });
      }
      return Promise.resolve();
    });
  } else {
    alert("登录已经过期，请先点击右上角重新登录");
    return Promise.reject("登录已经过期，请先点击右上角重新登录");
  }
}

async function manualVerifyPageGoods({
  multiplierMinInput = 1,
  multiplierMaxInput = 1,
  action,
  skuInfoMap,
  platform,
  shopId,
}: TManualVerifyGoods): Promise<{ action: string }> {
  try {
    await formatSkuListToSkuInfoMap({
      skuInfoMap,
      platform,
      shopId,
      multiplierMinInput,
      multiplierMaxInput,
      operateMap: {},
    });
    await awaitDelayTime();
    return Promise.resolve({
      action: "end",
    });
  } catch (error) {
    return Promise.reject(error);
  }
}

// 添加商品
function findBtnGroupElement() {
  const btnGroupElement = document.querySelector(
    '[class*="mrs_styles__btn-ground--"'
  );
  return btnGroupElement;
}
function findAddGoodsBtnElement() {
  const btnGroupElement = findBtnGroupElement();
  if (btnGroupElement) {
    // 找到 btnGroupElement 下 class 只有 "so-button so-button-primary" 的 button 元素
    const buttons = btnGroupElement.querySelectorAll("button");
    for (const btn of Array.from(buttons)) {
      if (
        btn.classList.length === 2 &&
        btn.classList.contains("so-button") &&
        btn.classList.contains("so-button-primary")
      ) {
        return btn;
      }
    }
  }
  return null;
}
function findUploadGoodsXlsxBtnElement() {
  const btnGroupElement = findBtnGroupElement();
  if (btnGroupElement) {
    // 找到 btnGroupElement 下 class 只有 "so-button so-button-primary" 的 button 元素
    const buttons = btnGroupElement.querySelectorAll("button");
    for (const btn of Array.from(buttons)) {
      if (
        btn.classList.length === 3 &&
        btn.classList.contains("so-button") &&
        btn.classList.contains("so-button-primary") &&
        btn.classList.contains("so-button-outline")
      ) {
        return btn;
      }
    }
  }
  return null;
}

function getSelfPlatformAddGoodsApiPayload() {
  return sendMessage({
    type: "getSelfPlatformAddGoodsApiPayload",
  });
}
function getSelfPlatformCreateActivePayload() {
  return sendMessage({
    type: "getSelfPlatformCreateActivePayload",
  });
}

function getGoodsList(params: any) {
  return fetch(`${originUrl}/mrs-api-prefix/promotion/limited/query_goods`, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify(params),
  }).then((res) => {
    return res.json().then((resData) => {
      return resData;
    });
  });
}

async function startAutoAddGoods({
  action,
  data,
}: {
  action: string;
  data: any;
}) {
  // 显示loading
  const baoyiCustomPlugLoadingManager = (window as any)
    .baoyiCustomPlugLoadingManager;
  if (baoyiCustomPlugLoadingManager) {
    baoyiCustomPlugLoadingManager.show("正在获取商品数据...");
  }

  try {
    const finalGoodsList = await getGoodsListData({
      data,
      startPageNum: 1,
    });
    if (!finalGoodsList.length) {
      if (baoyiCustomPlugLoadingManager) {
        baoyiCustomPlugLoadingManager.hide();
      }
      alert("暂无符合条件的商品可以添加");
      return;
    }
    const uploadGoodsXlsxBtnElement = findUploadGoodsXlsxBtnElement();
    if (!uploadGoodsXlsxBtnElement) {
      if (baoyiCustomPlugLoadingManager) {
        baoyiCustomPlugLoadingManager.hide();
      }
      return;
    }
    uploadGoodsXlsxBtnElement.click();

    // 生成 XLSX 并上传到 fileInput：列为「skc（必填）| 活动价」
    try {
      const headers = ["skc（必填）", "活动价"];
      const dataRows = finalGoodsList.map((item: any) => ({
        "skc（必填）": item.skc,
        活动价: item.__finallyPrice,
      }));

      const ws = XLSX.utils.json_to_sheet(dataRows, { header: headers });
      // 设置表头顺序
      XLSX.utils.sheet_add_aoa(ws, [headers], { origin: "A1" });

      const wb = XLSX.utils.book_new();
      XLSX.utils.book_append_sheet(wb, ws, "SKC列表");

      const wbout = XLSX.write(wb, { bookType: "xlsx", type: "array" });
      const blob = new Blob([wbout], {
        type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
      });

      // 创建 File 对象并上传到 fileInput
      const fileName = `skc_list_${Date.now()}.xlsx`;
      const file = new File([blob], fileName, {
        type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
      });

      setTimeout(async () => {
        let fileInput = document.querySelector(
          ".so-modal .so-upload-handle input"
        ) as HTMLInputElement;
        if (!fileInput) {
          const confirmBtn = document.querySelector(
            "[class*='mrs_styles__modal-footer-btn--'] .so-button-primary"
          ) as HTMLButtonElement;
          if (confirmBtn) {
            confirmBtn.click();
            await sleep(1000);
            fileInput = document.querySelector(
              ".so-modal .so-upload-handle input"
            ) as HTMLInputElement;
          }
          if (!fileInput) {
            if (baoyiCustomPlugLoadingManager) {
              baoyiCustomPlugLoadingManager.hide();
            }
            alert("找不到 fileInput 元素");
            return;
          }
        }

        // 使用正确的方式触发文件上传
        const dataTransfer = new DataTransfer();
        dataTransfer.items.add(file);
        fileInput.files = dataTransfer.files;

        // 手动触发 change 事件
        const changeEvent = new Event("change", { bubbles: true });
        fileInput.dispatchEvent(changeEvent);

        // 触发 input 事件（某些组件可能需要）
        const inputEvent = new Event("input", { bubbles: true });
        fileInput.dispatchEvent(inputEvent);

        setTimeout(() => {
          const confirmBtn = document.querySelector(
            ".so-modal .so-button-primary"
          ) as HTMLElement;
          if (confirmBtn) {
            confirmBtn.click();
          }
          // 隐藏loading
          if (baoyiCustomPlugLoadingManager) {
            baoyiCustomPlugLoadingManager.hide();
          }
        }, 500);
      }, 1500);
    } catch (e) {
      // 异常情况下也要隐藏loading
      if (baoyiCustomPlugLoadingManager) {
        baoyiCustomPlugLoadingManager.hide();
      }
      alert("生成 XLSX 失败，请检查是否已正确引入 SheetJS");
    }
  } catch (e) {
    // 外层异常处理
    if (baoyiCustomPlugLoadingManager) {
      baoyiCustomPlugLoadingManager.hide();
    }
    alert("操作失败：" + e);
  }
}

async function getPayloadData() {
  const addGoodsBtn = findAddGoodsBtnElement();
  if (!addGoodsBtn) {
    alert("找不到添加商品按钮");
    return;
  }
  addGoodsBtn.click();
  let payloadData: Record<string, any> | null = null;
  for (let i = 0; i < 5; i++) {
    await sleep(1000);
    const { page_num, page_size, ...payload } =
      ((await getSelfPlatformAddGoodsApiPayload()) || {}) as Record<
        string,
        any
      >;
    if (payload && Object.keys(payload).length > 0) {
      payloadData = payload;
      payloadData = payload;
      const closeBtnElement = document.querySelector(
        ".so-modal-close"
      ) as HTMLElement;
      if (closeBtnElement) {
        closeBtnElement.click();
      }
      return payloadData;
    }
  }
  alert("未获取到有效的 payload，请稍后重试");
  return;
}

// 价格范围写死，shein没有规定，按照
const MIN_RATE_VALUE = 0.05;
const MAX_RATE_VALUE = 0.8;

async function filterGoodsDataByErpPriceMap({
  enableGoodsData,
  shopId,
  platform,
  baoyiplus_accessToken,
  multiplierMinInput,
  multiplierMaxInput,
  isOnlyAddGoods,
}: {
  enableGoodsData: any[];
  shopId: string;
  platform: string;
  baoyiplus_accessToken: string;
  multiplierMinInput: number;
  multiplierMaxInput: number;
  isOnlyAddGoods: boolean;
}) {
  if (isOnlyAddGoods) {
    return enableGoodsData;
  }
  const skuCodeList = enableGoodsData.reduce((list, item) => {
    const { sku_info_list } = item;
    (sku_info_list || []).forEach((skuInfo: any) => {
      const sku = skuInfo.sku;
      if (sku) {
        list.push(sku);
      }
    });
    return list;
  }, []);
  const erpSKuPriceMap = await getErpSkuPriceMap({
    skuCodeList,
    shopId,
    platform,
    baoyiplus_accessToken,
  });

  if (!Object.keys(erpSKuPriceMap).length) {
    return [];
  }
  const list: any[] = [];
  const promiseArray = enableGoodsData.map((goods) => {
    return (async () => {
      const { sale_price, currency, sku_info_list } = goods;
      const hasMultipleSku = sku_info_list.length > 1;
      const skuFinallyPriceMap: any = {};

      const checkSkuCodePriceArray = sku_info_list.map((skuInfo: any) => {
        const sku = skuInfo.sku;
        return (async () => {
          const erpPriceInfo = erpSKuPriceMap[sku];
          if (!erpPriceInfo) {
            return;
          }
          const { sourcePrice, sourceCurrency } = erpPriceInfo as any;
          const editInputPrice = await converter.convert(
            sourcePrice,
            sourceCurrency,
            currency
          );
          const finallyPrice = calculateMaxInputAmountOptimized({
            currencyPrice: Number(sale_price),
            reduceRateRange: { min: MIN_RATE_VALUE, max: MAX_RATE_VALUE }, // 这边不是范围而是最大值
            multiplierMinInput,
            multiplierMaxInput,
            purchasePrice: editInputPrice,
          });
          skuFinallyPriceMap[sku] = finallyPrice;
        })();
      });

      await Promise.all(checkSkuCodePriceArray);
      const skuPriceList = Object.values(skuFinallyPriceMap);
      const isAllSKuHaveFinallyPrice = skuPriceList.every((price) => !!price);
      if (
        skuPriceList.length &&
        isAllSKuHaveFinallyPrice &&
        skuPriceList.length === 1
      ) {
        if (hasMultipleSku) {
          list.push({
            ...goods,
            sku_info_list: sku_info_list.map((item: any) => {
              return {
                ...item,
                __finallyPrice: skuFinallyPriceMap[item.sku],
              };
            }),
          });
        } else {
          list.push({
            ...goods,
            __finallyPrice: skuPriceList[0],
          });
        }
      }
    })();
  });
  await Promise.all(promiseArray);

  return list;
}

async function filterGoodsDataByPlatformPriceMap({
  enableGoodsData,
  platformPricePercentage,
}: {
  enableGoodsData: any[];
  platformPricePercentage: number;
}): Promise<any[]> {
  const data: any[] = enableGoodsData.reduce((list, goods) => {
    const { sale_price, sku_info_list } = goods;
    const hasMultipleSku = sku_info_list.length > 1;
    const doPricePercentage = (100 - Number(platformPricePercentage)) / 100;
    list.push({
      ...goods,
      __finallyPrice: Number(
        (Number(sale_price) * doPricePercentage).toFixed(2)
      ),
      sku_info_list: sku_info_list.map((item: any) => {
        if (hasMultipleSku) {
          return {
            ...item,
            __finallyPrice: Number(
              (Number(item.sale_price) * doPricePercentage).toFixed(2)
            ),
          };
        }
        return item;
      }),
    });
    return list;
  }, []);

  return Promise.resolve(data);
}

async function filterGoodsDataByPriceMap({
  enableGoodsData,
  shopId,
  platform,
  baoyiplus_accessToken,
  multiplierMinInput,
  multiplierMaxInput,
  isOnlyAddGoods,
  priceSource,
  platformPricePercentage,
}: {
  enableGoodsData: any[];
  shopId: string;
  platform: string;
  baoyiplus_accessToken: string;
  multiplierMinInput: number;
  multiplierMaxInput: number;
  isOnlyAddGoods: boolean;
  priceSource: string;
  platformPricePercentage: number;
}): Promise<any[]> {
  if (priceSource === "platformPrice") {
    return filterGoodsDataByPlatformPriceMap({
      enableGoodsData,
      platformPricePercentage,
    });
  } else if (priceSource === "erpPrice") {
    return filterGoodsDataByErpPriceMap({
      enableGoodsData,
      shopId,
      platform,
      baoyiplus_accessToken,
      multiplierMinInput,
      multiplierMaxInput,
      isOnlyAddGoods,
    });
  }
  return Promise.resolve(enableGoodsData);
}

// 获取shein后台商品列表并根据ERP价格和填写的倍率获取最后验证通过的商品
async function getGoodsListData({
  data,
  startPageNum = 1,
}: {
  data: any;
  startPageNum: number;
}) {
  const {
    shopId,
    platform,
    baoyiplus_accessToken,
    multiplierMinInput,
    multiplierMaxInput,
    addGoodsNumber,
    isOnlyAddGoods = false,
    priceSource,
    platformPricePercentage,
    pluginMode,
    addGoodsNumber2,
  } = data;
  const uploadNumber =
    pluginMode === "quickMode"
      ? Number(addGoodsNumber2) || 500
      : Number(addGoodsNumber) || 500;

  const payloadData = await getPayloadData();
  const page_size = 500;
  const goodsList: any[] = [];
  let totalPage = 0;
  let shouldStop = false;

  // 首先获取第一页来确定总页数
  const firstPageData = await getGoodsList({
    ...payloadData,
    page_num: startPageNum,
    page_size,
  });

  if (firstPageData?.info?.meta?.count) {
    const total = Number(firstPageData.info.meta.count);
    totalPage = Math.ceil(total / page_size);

    // 处理第一页数据
    const firstPageGoods = (firstPageData?.info?.data || []) as any[];
    const enableGoodsData = firstPageGoods.filter((goods) => {
      return !goods?.error_code;
    });
    if (enableGoodsData.length) {
      const filteredGoodsData = await filterGoodsDataByPriceMap({
        enableGoodsData,
        shopId,
        platform,
        baoyiplus_accessToken,
        multiplierMinInput,
        multiplierMaxInput,
        isOnlyAddGoods,
        priceSource,
        platformPricePercentage,
      });
      goodsList.push(...filteredGoodsData);
    }
  }

  // 如果已经获取到足够的数据，直接返回
  if (goodsList.length >= uploadNumber) {
    shouldStop = true;
  }

  if (!shouldStop && totalPage > 1) {
    // 创建并发执行器

    // 创建任务数组，从第2页开始
    const tasks = [];
    for (let page_num = startPageNum + 1; page_num <= totalPage; page_num++) {
      tasks.push(async () => {
        if (shouldStop) return;

        const resData = await getGoodsList({
          ...payloadData,
          page_num,
          page_size,
        });

        const goodsDataList = (resData?.info?.data || []) as any[];
        const enableGoodsData = goodsDataList.filter((goods) => {
          return !goods?.error_code;
        });

        // 直接添加所有有效数据，不在这里限制数量
        if (enableGoodsData.length) {
          const filteredGoodsData = await filterGoodsDataByPriceMap({
            enableGoodsData,
            shopId,
            platform,
            baoyiplus_accessToken,
            multiplierMinInput,
            multiplierMaxInput,
            isOnlyAddGoods,
            priceSource,
            platformPricePercentage,
          });
          goodsList.push(...filteredGoodsData);
        }

        // 检查是否达到目标数量
        if (goodsList.length >= uploadNumber) {
          shouldStop = true;
        }
      });
    }

    // 并发执行所有任务
    await concurrentExecutor.execute(tasks);
  }

  // 最后统一处理数量限制
  const finalGoodsList = goodsList.slice(0, uploadNumber);
  return finalGoodsList;
}

function createActivity(params: any) {
  return new Promise((resolve, reject) => {
    fetch(`${originUrl}/mrs-api-prefix/promotion/limited/create_activity`, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify(params),
    })
      .then((res) => {
        res
          .json()
          .then((resData) => {
            if (Number(resData.code) === 0) {
              resolve(true);
            } else {
              reject(resData?.msg || "创建活动接口请求错误");
            }
          })
          .catch((error) => {
            reject(error || `创建活动接口解析返回错误， res => ${res}`);
          });
      })
      .catch((error) => {
        reject(error || "创建活动接口请求错误");
      });
  });
}

async function startQuickMode({ action, data }: { action: string; data: any }) {
  const baoyiCustomPlugLoadingManager = (window as any)
    .baoyiCustomPlugLoadingManager;
  if (baoyiCustomPlugLoadingManager) {
    baoyiCustomPlugLoadingManager.show("正在获取商品数据...");
  }
  const storage = await chrome.storage.sync.get(["baoyiplus_accessToken"]);
  const { baoyiplus_accessToken = "" } = storage;
  if (baoyiplus_accessToken) {
    try {
      const startTime = Math.floor(Date.now() / 1000);

      const finalGoodsList = await getGoodsListData({
        data: {
          ...data,
          baoyiplus_accessToken,
        },
        startPageNum: 1,
      });
      if (!finalGoodsList.length) {
        if (baoyiCustomPlugLoadingManager) {
          baoyiCustomPlugLoadingManager.hide();
        }
        alert("暂无符合条件的商品可以添加");
        return;
      }
      const createBaseParams: any = await getSelfPlatformCreateActivePayload();
      if (!createBaseParams) {
        if (baoyiCustomPlugLoadingManager) {
          baoyiCustomPlugLoadingManager.hide();
        }
        alert("获取不到创建活动的参数");
        return;
      }

      // 活动限量，为1则不限量。2则为限量
      const isActiveStockLimit = Number(createBaseParams.sub_type_id) === 2;

      const productList = finalGoodsList.map((goodsItem) => {
        const {
          skc,
          stock,
          currency,
          is_sale_attribute,
          sale_price,
          sku_info_list,
          __finallyPrice,
        } = goodsItem;
        if (!__finallyPrice) {
          return {
            skc,
            is_sale_attribute,
            skc_operate_type: 1, // TODO ZCH 没找到这个字段
            attend_num_sum: isActiveStockLimit ? stock : 0,
            stock_num: stock,
            sku_list: sku_info_list.map((skuInfoItem: any) => {
              const { sku, currency, __finallyPrice, sale_price } = skuInfoItem;
              return {
                sku,
                sku_operate_type: 1, // TODO ZCH 没找到这个字段，上面还有一个skc_operate_type
                currency,
                attend_price: __finallyPrice,
                sale_price,
              };
            }),
          };
        }
        return {
          skc,
          currency,
          is_sale_attribute,
          skc_operate_type: 1, // TODO ZCH 没找到这个字段
          attend_num_sum: isActiveStockLimit ? stock : 0,
          stock_num: stock,
          sale_price,
          attend_price: __finallyPrice || 0, // TODO ZCH
          sku_list: sku_info_list.map((skuInfoItem: any) => {
            const { sku, currency } = skuInfoItem;
            return {
              sku,
              sku_operate_type: 1, // TODO ZCH 没找到这个字段，上面还有一个skc_operate_type
              product_act_price: 0,
              max_product_act_price: 0,
              cost_price: 0,
              currency,
            };
          }),
        };
      });
      const productListChunkList = chunkArray(productList, 500);
      for (let i = 0; i < productListChunkList.length; i++) {
        const { zone_start_time } = createBaseParams;
        const currentTime = Math.floor(Date.now() / 1000);
        const diffTime = currentTime - startTime;
        let nowZoneStartTime = "";
        if (zone_start_time) {
          const baseTs = parseDateTimeToTs(zone_start_time);
          const newTs = baseTs + diffTime;
          nowZoneStartTime = formatTsToDateTime(newTs);
        } else {
          nowZoneStartTime = "";
        }
        const timeText = getCurrentTimeText();
        const params = {
          ...createBaseParams,
          zone_start_time: nowZoneStartTime || zone_start_time,
          act_name: `限时限量购${timeText}`,
          product_list: productListChunkList[i],
        };
        await createActivity(params);
      }

      baoyiCustomPlugLoadingManager.hide();

      showCustomDialog({
        message: "创建成功",
        buttons: [
          {
            label: "前往查看",
            onClick: () => {
              window.location.href = `${originUrl}/#/mrs/tools/list/1/0`;
            },
          },
          {
            label: "继续创建",
            onClick: () => {
              window.location.href = `${originUrl}/#/mrs/tools/list`;
            },
          },
        ],
      });
    } catch (error) {
      alert(error);
      baoyiCustomPlugLoadingManager.hide();
    }
  } else {
    alert("获取不到登录信息，请登录后重试");
    baoyiCustomPlugLoadingManager.hide();
  }
}

export default {
  manualVerifyPageGoods,
  startAutoAddGoods,
  startQuickMode,
};
